var wxCharts = require('../../utils/wxcharts.js');
var Api = require('../../utils/api.js');
var columnChart = null;
var targetData = [5000, 5000, 5000, 5000];  // 目标步数（四天）
var currentData = [0, 0, 0, 0];              // 实际步数（四天）
var dateLabels = ['', '', '', ''];           // 日期标签（四天）

Page({
  data: {
    // 运动目标列表
    sports: [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000],
    sportIndex: 2,

    // 标签
    tabs: ["运动记录"],

    // 列表切换
    TabCur: 0,

    // 运动数据
    eat: {
      eat_score: 0,
      sport: [],
      score: {
        first_target: 5000,
        second_target: 5000,
        third_target: 5000,
        fourth_target: 5000,
        first_step: 0,
        second_step: 0,
        third_step: 0,
        fourth_step: 0,
        first_date: "",
        second_date: "",
        third_date: "",
        fourth_date: "",
        // 运动消耗营养
        calorie_burn: 0,
        fat_burn: 0,
        carbohydrate_burn: 0,
        protein_burn: 0
      },
      exercise: 5000,
    },

    openid: "",
    ListTouchStart: 0,
    ListTouchDirection: "",
    modalName: null,
    code: "",
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
    });
  },
  onShareAppMessage(o) {},

  onShow: function () {
    this.indexData();
  },

  onLoad: function() {
    // 页面加载时获取微信运动数据
    this.getWeRunData();
  },

  // 获取微信运动数据
  getWeRunData: function() {
    const that = this;
    
    // 1. 先调用 wx.login 获取 code
    wx.login({
      success: function(loginRes) {
        if (loginRes.code) {
          const code = loginRes.code;
          
          // 2. 获取微信运动数据授权
          wx.getWeRunData({
            success: function(weRunRes) {
              console.log('获取微信运动数据成功');
              
              // 3. 将加密数据发送到后端解密
              wx.request({
                url: Api.run(),
                method: 'POST',
                data: {
                  encryptedData: weRunRes.encryptedData,
                  iv: weRunRes.iv,
                  code: code
                },
                success: function(res) {
                  console.log('步数数据保存成功:', res.data);
                  wx.showToast({
                    title: '步数数据已更新',
                    icon: 'success'
                  });
                  // 重新加载页面数据
                  that.indexData();
                },
                fail: function(err) {
                  console.error('步数数据保存失败:', err);
                  wx.showToast({
                    title: '步数数据获取失败',
                    icon: 'none'
                  });
                }
              });
            },
            fail: function(err) {
              console.log('获取微信运动数据失败:', err);
              
              // 如果是用户拒绝授权，引导用户授权
              if (err.errMsg.indexOf('auth deny') !== -1 || err.errMsg.indexOf('authorize') !== -1) {
                wx.showModal({
                  title: '提示',
                  content: '需要获取您的微信运动数据权限，以显示每日步数',
                  success: function(modalRes) {
                    if (modalRes.confirm) {
                      // 打开设置页面
                      wx.openSetting({
                        success: function(settingRes) {
                          if (settingRes.authSetting['scope.werun']) {
                            // 用户授权成功，重新获取数据
                            that.getWeRunData();
                          }
                        }
                      });
                    }
                  }
                });
              } else {
                // 其他错误，继续显示数据库中的数据
                console.log('使用数据库中的步数数据');
                that.indexData();
              }
            }
          });
        } else {
          console.error('登录失败:', loginRes.errMsg);
          // 登录失败，继续显示数据库中的数据
          that.indexData();
        }
      },
      fail: function(err) {
        console.error('wx.login 失败:', err);
        // 登录失败，继续显示数据库中的数据
        that.indexData();
      }
    });
  },

  // 从后端获取运动数据
  indexData: function () {
    var that = this;
    
    // 使用Do模型获取运动数据
    wx.request({
      url: Api.do(),
      method: 'GET',
      success: function(res) {
        console.log("获取运动数据成功:", res.data);
        if (res.data) {
          const sportData = res.data;
          
          // 更新标签显示运动记录数量
          const tabs = [`运动记录(${sportData.sport ? sportData.sport.length : 0})`];
          
          that.setData({
            eat: sportData,
            tabs: tabs,
            sportIndex: that.data.sports.indexOf(sportData.exercise || 5000)
          });
          
          // 从score字段获取真实的步数数据
          if (sportData.score) {
            const score = sportData.score;
            
            // 目标步数（四天）
            targetData = [
              score.first_target || 5000,
              score.second_target || 5000,
              score.third_target || 5000,
              score.fourth_target || 5000
            ];
            
            // 实际步数（四天）
            currentData = [
              score.first_step || 0,
              score.second_step || 0,
              score.third_step || 0,
              score.fourth_step || 0
            ];
            
            // 日期标签（四天）
            dateLabels = [
              score.first_date || '',
              score.second_date || '',
              score.third_date || '',
              score.fourth_date || ''
            ];
          }
          
          // 绘制图表
          that.canvas();
        }
        wx.stopPullDownRefresh();
      },
      fail: function(err) {
        console.error("获取运动数据失败:", err);
        // 使用默认数据
        const score = that.data.eat.score;
        targetData = [
          score.first_target,
          score.second_target,
          score.third_target,
          score.fourth_target
        ];
        currentData = [
          score.first_step,
          score.second_step,
          score.third_step,
          score.fourth_step
        ];
        dateLabels = [
          score.first_date,
          score.second_date,
          score.third_date,
          score.fourth_date
        ];
        that.canvas();
        wx.stopPullDownRefresh();
      }
    });
  },

  canvas: function () {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error("getSystemInfoSync failed!");
    }

    // 绘制步数图表（四天数据）
    columnChart = new wxCharts({
      canvasId: "columnCanvas",
      type: "column",
      animation: true,
      categories: dateLabels,  // 使用日期作为X轴标签
      series: [
        {
          name: "目标步数",
          data: targetData,
          format: function (val, name) {
            return val;
          },
        },
        {
          name: "每日步数",
          data: currentData,
          format: function (val, name) {
            return val;
          },
        },
      ],
      yAxis: {
        format: function (val) {
          return val;
        },
        title: "四日运动步数",
        min: 0,
      },
      xAxis: {
        disableGrid: true,
        type: "calibration",
      },
      extra: {
        column: {
          width: 15,
        },
      },
      width: windowWidth,
      height: 200,
    });
  },

  // 列表触摸事件的模拟处理
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX,
    });
  },

  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > -100 ? "right" : "left",
    });
  },

  ListTouchEnd(e) {
    if (this.data.ListTouchDirection === "left") {
      this.setData({
        modalName: e.currentTarget.dataset.target,
      });
    } else {
      this.setData({
        modalName: null,
      });
    }
    this.setData({
      ListTouchDirection: null,
    });
  },

  goToSearch(e) {
    wx.navigateTo({
      url: "/pages/search/search?eat_type=0",
    });
  },

  goToEatReport(e) {
    wx.navigateTo({
      url: "/pages/eat-report/eat-report",
    });
  },

  bindSportChange: function (e) {
    const that = this;
    const sportIndex = e.detail.value;
    const exercise = this.data.sports[sportIndex];
    
    this.setData({
      sportIndex: sportIndex
    });
    
    // 更新后端的步数目标
    wx.request({
      url: Api.do(),
      method: 'PUT',
      data: {
        exercise: exercise
      },
      success: function(res) {
        console.log("更新步数目标成功:", exercise);
        that.indexData(); // 重新加载数据
      },
      fail: function(err) {
        console.error("更新步数目标失败:", err);
      }
    });
  },

  onPullDownRefresh: function () {
    console.log("Pull down to refresh data");
    this.indexData();
  },

  // 删除运动记录
  eatDelete: function(e) {
    const that = this;
    const index = e.currentTarget.dataset.index;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条运动记录吗？',
      success: function(res) {
        if (res.confirm) {
          // 从运动数组中删除指定项
          const updatedSport = [...that.data.eat.sport];
          updatedSport.splice(index, 1);
          
          // 更新到后端
          wx.request({
            url: Api.do(),
            method: 'PUT',
            data: {
              sport: updatedSport
            },
            success: function(response) {
              console.log("删除运动记录成功");
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              // 重新加载数据
              that.indexData();
            },
            fail: function(err) {
              console.error("删除运动记录失败:", err);
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  }
});
